<?php
require_once '../data/data.php';

session_start();

//只支持POST请求，否则返回405错误
if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
   header('HTTP/1.1 405 Method Not Allowed');
   return;
}

// 获取请求中的用户输入数据
$userName = isset($_POST['userName']) ? htmlspecialchars($_POST['userName']) : '';
$password = isset($_POST['password']) ? htmlspecialchars($_POST['password']) : '';

// $hasError = false;
$hasError = true;
 $errorBag['password'] = '用户名或密码错误';

$errorBag = [
	'userName' => '',
	'password' => ''
];

if (trim($userName) == '') {
$hasError = true;
$errorBag['userName'] = '用户名不得为空';
}

if ($password == '') {
  $hasError = true;
  $errorBag['password'] = '密码不得为空';
}

// 根据用户名查找用户记录
$sql = 'select id,user_name,password from users where user_name=?';
$data = query($sql, [$userName]);
if (count($data) > 0) {
  // 用户名正确，会查询到用户记录，则验证密码
  $user = $data[0];
  if (password_verify($password, $user['password'])) {
    // 密码正确, 做登录正确的处理
    $hasError = false;
    // 修改登录时间和ip
    $ip = $_SERVER['REMOTE_ADDR'];
    $sql = 'update users set last_login=now(),last_login_ip=? where id=?';
    $args = [$ip, $user['id']];
    execute($sql, $args);
    //用户密码验证通过，把用户信息存入session，意味已登录
    $_SESSION['user'] = $user;
    header('Location:../../public/index.php');
    return;
  }
}

// 将错误包写入session
if ($hasError) {
   $_SESSION['has_error'] = $hasError;
   $_SESSION['error_bag'] = $errorBag;
   header('Location:../../public/register.php?op=2');
}
